package com.lsh.oms.core.proxy.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lsh.base.http.client.core.HttpClient;
import com.lsh.base.lang.Maps;
import com.lsh.oms.core.email.SendEmailService;
import com.lsh.oms.core.exception.BusinessException;
import com.lsh.oms.core.model.http.HttpMessage;
import com.lsh.oms.core.proxy.model.PoCodeSplit;
import com.lsh.oms.core.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

import static com.lsh.base.http.client.ResponseAssertions.success;

/**
 * Project Name: lsh-oms
 *
 * @author peter
 * @date 18/2/27
 * 北京链商电子商务有限公司
 * Package
 * desc:
 */
@Component
@Slf4j
public class PsiProxy extends BaseProxy {

    @Autowired
    private SendEmailService sendEmailService;

    private static final String CODE_2_PROVIDERID = "/api/wm/goodsVender";
    private static Logger logger = LoggerFactory.getLogger(TmsProxy.class);
    @Value("${po.psi.url}")
    private String psiHost;

    @Resource(name = "apache.http.client")
    private HttpClient https;


    private static Header[] getRequestHeader() {
        Header[] headers = {new BasicHeader("Accept", "application/json"), new BasicHeader("Content-type", "application/json")};
        return headers;
    }

    public Map<String, Object> reportLoss(Map<String, Object> request, Long venderId) {
        Map<String, Object> response = https.post(psiHost + "/api/rso/createDamage", Maps.newHashMap("venderId", venderId), request);
        if (!success(response)) {
            throw BusinessException.badRequest("创建货损单失败");
        }
        return response;
    }

    private String request(String data) {
        String url = psiHost + CODE_2_PROVIDERID;

        String message = "[PsiProxy][code2venderIdrId]";
        String responseData = "";
        try {
            HttpMessage httpMessage = HttpUtils.sendPostRequest(url, data, getRequestHeader());
            responseData = httpMessage.getMessage();
            if (responseData == null) {
                responseData = "";
            }
            logger.info(message + " responseData:" + responseData);
        } catch (IOException e) {
            logger.error("{}[error][Error message]:{}", message, e.getMessage());
        }

        return responseData;
    }

    public List<PoCodeSplit> code2venderId(String data, Long orderCode) {

        String responseData = this.request(data);
        JSONObject res = JSON.parseObject(responseData);
        String ret = res.getString("ret");
        if (StringUtils.isEmpty(ret)) {
            return Collections.EMPTY_LIST;
        }

        if (!"0".equals(ret)) {

            String msg = res.getString("msg");
            log.info(orderCode + ":" + msg);
            this.sendEmail(orderCode, msg);

            return Collections.EMPTY_LIST;
        }

        JSONObject content = res.getJSONObject("content");
        if (content == null) {
            return Collections.EMPTY_LIST;
        }

        JSONArray list = content.getJSONArray("list");
        if (list.isEmpty()) {
            return Collections.EMPTY_LIST;
        }

        Map<String, List<String>> resMap = new HashMap<>();
        for (int i = 0; i < list.size(); i++) {

            JSONObject goods = list.getJSONObject(i);

            String code = goods.getString("goods_id");
            String vender_id = goods.getString("vender_id");

            List<String> codeList = resMap.get(vender_id);
            if (CollectionUtils.isEmpty(codeList)) {
                codeList = new ArrayList<>();

                resMap.put(vender_id, codeList);
            }

            codeList.add(code);
        }

        List<PoCodeSplit> poCodeSplitList = new ArrayList<>();

        for (Map.Entry<String, List<String>> entry : resMap.entrySet()) {
            PoCodeSplit poCodeSplit = new PoCodeSplit();
            poCodeSplit.setVenderId(entry.getKey());
            poCodeSplit.setCodes(entry.getValue());

            poCodeSplitList.add(poCodeSplit);
        }

        return poCodeSplitList;
    }

    /**
     * 处理失败邮件发送
     *
     * @param orderCode 订单号
     * @param msg       错误信息
     */
    private void sendEmail(Long orderCode, String msg) {
        if (msg.length() > 200) {
            msg = msg.substring(0, 200);
        }
        String message = orderCode + ":查询进销存主供商:" + msg;

        this.sendEmailService.asyncSendEmail(message, "商品查询主供商失败");
    }

}
